package com.yuncommunity.cloudlab

import com.google.gson.Gson
import com.yuncommunity.cloudlab.repository.UserRepository
import com.yuncommunity.cloudlab.utils.MyResult
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.servlet.HandlerInterceptor
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Component
class AdminInterceptor : HandlerInterceptor {
    @Autowired
    lateinit var userRepository: UserRepository

    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        var token = request.getParameter("token")
        var out = response.outputStream
        if (token == null) {
            out.write(Gson().toJson(MyResult(-1, "请登录")).toByteArray())
            return false
        }
        var user = userRepository.findByToken(token)
        if (user == null) {
            out.write(Gson().toJson(MyResult(-1, "登录已过期,请重新登录")).toByteArray())
            return false
        }
        return super.preHandle(request, response, handler)
    }
}